#!/usr/bin/env python
# coding: utf-8
import web
from config import settings
from datetime import datetime
import authbase

render = settings.render
db = settings.db
tb = 'stations'

def get_by_id(id):
    try:  
        return db.select(tb, where = 'id=$id', vars = locals())[0]  
    except IndexError:  
        return None 


class New(authbase.AuthBase):

    def GET(self):
        new_station=""
        return render.stations.new(new_station="")

class Create(authbase.AuthBase):

    def POST(self):
        i = web.input()
        name = i.get('name', None)
        if not name:
            return render.error('名称不能为空', None)
        db.insert(tb, name=name)
        raise web.seeother('/stations')


class Edit:

    def GET(self, id):
        station = get_by_id(int(id))
        if not station:
            return render.error('没找到这条记录', None)
        return render.stations.edit(new_station=station)

    def POST(self, id):
        station = get_by_id(int(id))
        if not station:
            return render.error('没找到这条记录', None)
        i = web.input()
        name = i.get('name', None)
        if not name:
            return render.error('名称不能为空', None)
        db.update(tb, name=name,updated_at=datetime.now(), where='id=$id', vars=locals())
        return render.error('编辑成功！', '/stations')

class Delete(authbase.AuthBase):

    def GET(self, id):
        station = get_by_id(int(id))
        if not station:
            return render.error('没找到这条记录', None)
        db.delete(tb, where='id=$id', vars=locals())
        return render.error('删除成功！', '/stations')


class Index(authbase.AuthBase):

    def GET(self):
        stations = db.select(tb)
        return render.stations.index(stations=stations)
